<template>
  <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
    <a-form-item ref="username" label="账号" name="username">
      <a-input v-model:value="formState.username" placeholder="请填写账号" />
    </a-form-item>
    <a-form-item ref="name" label="真实姓名" name="name">
      <a-input v-model:value="formState.name" placeholder="请填写真实姓名" />
    </a-form-item>
    <a-form-item v-if="showPasswordItem" ref="password" label="密码" name="password">
      <a-input v-model:value="formState.password" placeholder="请填写密码" />
    </a-form-item>
    <a-form-item label="角色" name="roles">
      <a-select v-model:value="formState.roles" mode="multiple" placeholder="请分配角色" class="select">
        <a-select-option value="user">普通用户</a-select-option>
        <a-select-option value="teacher">医生</a-select-option>
        <a-select-option value="admin">管理员</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="备注" name="desc">
      <a-textarea v-model:value="formState.desc" placeholder="请填写备注" />
    </a-form-item>
    <a-form-item class="submit-item">
      <a-button type="primary" block @click="handleSubmit">确定</a-button>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue"
import type { UnwrapRef } from "vue"
import type { Rule } from "ant-design-vue/es/form"

const formRef = ref()
const $emit = defineEmits(["submit"])
let showPasswordItem = ref<boolean>(true) //是否显示密码表单,仅仅[新增用户]时显示
const formState: UnwrapRef<any> = reactive({
  username: "",
  password: "",
  name: "",
  roles: [],
  desc: ""
})
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 5, message: "姓名长度为 2至5", trigger: "blur" }
  ],
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  roles: [
    {
      type: "array",
      required: true,
      message: "请选择角色",
      trigger: "blur"
    }
  ]
}

const handleSubmit = () => {
  let values: any = JSON.parse(JSON.stringify(formState))
  if (!showPasswordItem.value) {
    delete values["password"]
  }
  formRef.value.validate().then(() => {
    $emit("submit", values)
  })
}

defineExpose({ formState, showPasswordItem })
</script>
<style lang="scss" scoped>
:deep(.ant-form-item-label label) {
  font-size: 12px;
}
.select {
  width: 160px;
}
:deep(.select .ant-select-selector) {
  font-size: 12px;
}
:deep(.submit-item .ant-row) {
  display: flex;
  justify-content: center;
}
</style>
